#!/usr/bin/perl -w

use strict;
use warnings;
use WWW::Google::Cloud::Messaging;
use Net::Pcap::Easy;
use Data::Dumper;

my $api_key = 'AIzaSyA6X3oPhBN7j75vt7k-vK2dCX3jHlB_pIE';
my $gcm = WWW::Google::Cloud::Messaging->new(api_key => $api_key);
my $cat = "bel";

my $npe = Net::Pcap::Easy->new(
    dev              => "wlan0",
    filter           => "host 192.168.1.50 and udp",
    packets_per_loop => 10,
    bytes_to_capture => 1024,
    timeout_in_ms    => 0, # 0ms means forever
    promiscuous      => 0, # true or false
    
    udp_callback => sub {
        my ($npe, $ether, $ip, $udp, $header ) = @_;

        #print "UDP ($udp->{len}): $udp->{data})  \n";
        #print "RAW: ";
        #print unpack("H*", $udp->{data});
        #print "\n";
        
        my @data = split(undef,unpack("H*", $udp->{data}));
        my $identity = join('',@data[0..7]);
        my $id = join('',@data[8..15]);
        my $index = join('',@data[16..19]);
        my $subindex = join('',@data[20..23]);
        my $items = join('',@data[24..27]);
        my $length = join('',@data[28..31]);
        my $counter = join('',@data[32..35]);
        my $flags = join('',@data[36..37]);
        my $checksum = join('',@data[38..39]);
        my $data = join('',@data[40..41]);
        
        if ($index =~ /0100/ and $subindex =~ /0000/ and $data =~ /01/){
        	
		my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
								localtime(time);
		$year += "1900";

		my $date = "$year$mon$mday";
		my $time = "$hour$min$sec";

		my $msg = "Ding Dong!";

		my $string = "$date;$time;$cat;$msg";

		my $res = $gcm->send({
			registration_ids => [ 'APA91bF-KE92K2f6S6aI9vSpPHtVhFW4k0wsptSjIJOglChUA3cHjxd_njYHdWsNodAKQV8EzLNbVfYN63dt_i5fxPuARmySUKiPQnx7YmQdSMIc_ltm99yAxOvoM3vNVt3QorJOi7IACLNXsvw38fCdkYXqHnBysg' ],
#			time_to_live =>	 0,
			data             => {
			message => $string,
		      },
		});
	};
        #print "\t\t$data\n\n";
    }
);

1 while $npe->loop;
